import { Toast, Dialog } from "vant";
import cTitle from "components/title";
import purchaseNotes from "../consumptionComm/purchaseNotes/purchaseNotes";
import addressUs from "../consumptionComm/addressUs/addressUs";
import yzService from "components/ui_components/yz_service.vue";
export default {
  components: {
    purchaseNotes,
    addressUs,
    cTitle,
    yzService,
    Dialog
  },
  data() {
    return {
      orderShow: false, //开启优惠券弹窗
      imageRight: true,
      orderId: null,
      goodsId: null,
      refundId: null, //售后ID
      addressDetail: "",
      storeName: "", //商户名称
      couponStore: {}, //券码信息
      goodsDetail: {},
      couponList: [], //券码列表
      usableCoupon: [],
      couponCode: "",
      latitude: "",
      longitude: "",
      details: {},
      storeListByGoods: [], //商户列表信息
      total: 0,
      orderType: "shop",
      evaluateType: 0,
      succees: 0,
      //客服插件
      isMiniApp: window.isMiniprogram ? true : false,
      serviceShow: false,
      customerOpen: false,
      cservice: "",
      serviceQRcode: "",
      serviceMobile: "",
      //新加的企业微信数据显示
      clientType: '',
      client: '',
      member_id: ''
    };
  },
  activated() {
    this.orderId = Number(this.$route.query.orderId);
    this.member_id = Number(this.$route.query.member_id);
    this.clientType = this.$route.query.orderType;
    this.client = window.localStorage.getItem("client");
    //|| this.$route.query.orderType == 'coupon_store'
    if (this.fun.getKey('client') === 'work' || window.localStorage.getItem("client")) {
      //展示企业微信的订单详情数据
      let json = {
        order_id: this.orderId,
        order_type: this.clientType,
        basic_info: 1
      };
      this.companyDetails(json,'plugin.wechat-chat-sidebar.frontend.controller.customer.detail.index');
      return;
    }
    if (!this.client && this.$route.query.orderType == 'coupon_store') { //客户管理中心
      let json = {
        order_id: this.orderId,
        order_type: this.$route.query.orderType,
        member_id: this.member_id,
        basic_info: 1
      };
      this.companyDetails(json,'plugin.customer-center.frontend.controllers.customer.order-detail');
      return;
    }
    this.fun
      .getLocation()
      .then(res => {
        let p = this.fun.bd_encrypt(res.point.lng, res.point.lat);
        this.latitude = p.lat;
        this.longitude = p.lng;
        if (!this.client) {
          this.storeorderDetails();
          this.orderCoupon();
          this.serviceDetail();
        }
      })
      .catch(err => {
        console.log(err);
        this.locationStatus = false;
      });
  },
  methods: {
    companyDetails(json,api) {
      $http.get(api, json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.couponStore = res.coupon_store;
            this.details = res;
            this.goodsId = res.has_many_order_goods[0]?.goods_id;
            this.goodsDetail = res.has_many_order_goods[0];
            this.refundId = res.refund_id;
            this.storeName = res.coupon_store.coupon_list[0]?.has_one_store?.store_name;
            this.pluginSetting = response.basic_info?.plugin_setting?.coupon_store;
            this.couponList = res.cstore_order?.has_many_coupon || [];
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    storeorderDetails() {
      let json = {
        order_id: this.orderId,
        basic_info: 1
      };
      $http.get("order.detail", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.couponStore = res.coupon_store;
            this.details = res;
            this.goodsId = res.has_many_order_goods[0]?.goods_id;
            this.goodsDetail = res.has_many_order_goods[0];
            this.refundId = res.refund_id;
            this.storeName = res.coupon_store.coupon_list[0]?.has_one_store?.store_name;
            this.pluginSetting = response.basic_info?.plugin_setting?.coupon_store;
            this.getStoreListByGoods();
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    orderCoupon() {
      Toast.loading({
        message: "加载中...",
        forbidClick: true
      });
      let json = {
        order_id: this.orderId
      };
      $http.post("plugin.coupon-store.frontend.order.orderCoupon", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let couponList = res;
            let couponCode = "";
            let usableCoupon = [];
            couponCode = couponList.find(item => item.status === 0);
            usableCoupon = couponList.filter(item => item.status === 0);
            this.couponList = res;
            this.couponCode = couponCode;
            this.usableCoupon = usableCoupon;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    getStoreListByGoods() {
      let json = {
        goods_id: this.goodsId,
        store_name: "",
        longitude: this.longitude,
        latitude: this.latitude
      };
      $http.post("plugin.coupon-store.frontend.store.getStoreListByGoods", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let storeaddress = res.data;
            let addressDetail = `${storeaddress[0].city}${storeaddress[0].district}${storeaddress[0].street}${storeaddress[0].address}`;
            this.addressDetail = addressDetail;
            this.storeListByGoods = res.data;
            this.total = res.total;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    orderstateOn(params) {
      let {value, id, api} = params;
      console.log(value);
      //后端传的按钮api点击事件
      if (value === 9) {
        Dialog.confirm({
          title: "提示",
          message: "确定取消该订单?"
        })
          .then(() => {
            // on close
            this.cancelPay(id, api);
          })
          .catch(() => {
            // on cancel
          });
      }
      if (value === 1) {
        this.$router.push(this.fun.getUrl("orderpay", { order_ids: id, status: "2" }));
      }
    },
    cancelPay(id, api) {
      let json = {
        order_id: id
      };
      $http.post(api, json, "正在获取").then(
        response => {
          if (response.result == 1) {
            Toast(response.msg);
            this.storeorderDetails();
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    copyCode() {
      Toast("复制成功");
    },
    onError() {
      Toast("复制成功");
    },
    serviceDetail() {
      $http.post("goods.customer-service.index", { goods_id: this.orderId }, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.cservice = res.cservice;
            this.serviceQRcode = res.service_QRcode;
            this.serviceMobile = res.service_mobile;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    refreshCode() {
      //刷新扫码的二维码信息
      this.orderCoupon();
    },
    navigationLocation() {
      wx.navigateTo({
        url: "/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=storeApply"
      });
    },
    shopNavTo() {
      this.$router.push(
        this.fun.getUrl(
          "shopList",
          {},
          {
            goodsId: this.goodsId,
            longitude: this.longitude,
            latitude: this.latitude
          }
        )
      );
    },
    onClose() {
      this.orderShow = false;
    },
    onQrcode() {
      this.orderShow = true;
    },
    evaluateBtn(storeName) {
      this.$router.push(
        this.fun.getUrl(
          "conevaluate",
          {},
          {
            orderId: this.orderId,
            type: 1,
            storeName: storeName
          }
        )
      );
    },
    refundBtn() {
      this.$router.push(
        this.fun.getUrl(
          "refundOrder",
          {},
          {
            orderId: this.orderId,
            type: 2,
            orderType: 1
          }
        )
      );
    },
    afterSaleBtn() {
      this.$router.push(
        this.fun.getUrl(
          "refundProcess",
          {},
          {
            refundId: this.refundId
          }
        )
      );
    },
    closePop() {
      this.serviceShow = false;
    },
    clickChat() {
      let setServicePlugin = this.fun.isTextEmpty(this.serviceMobile) && this.fun.isTextEmpty(this.serviceQRcode);
      if (this.fun.isTextEmpty(this.cservice) && setServicePlugin) {
        return this.$toast("抱歉，暂未设置客服信息");
      }
      if (!this.fun.isTextEmpty(this.cservice) && setServicePlugin) {
        //只设置了客服链接，直接跳转
        if (this.cservice && this.cservice.indexOf("chatWindow") >= 0) {
          window.location.href = this.cservice + "&goods_id=" + this.$route.params.id;
        } else {
          window.location.href = this.cservice;
        }
        return;
      }
      this.serviceShow = true;
    }

  }
};
